<?php

namespace app\api\controller;

use addons\third\model\Third as thirdModel;
use app\common\controller\Api;
use app\common\model\User;
use app\common\library\Sms;
use think\Config;
use think\Cookie; // 增加事件 by Fire
use think\Hook; // 增加事件 by Fire
use think\Validate;
use fast\Http;
use fast\Random;
use think\Debug;

/**
 * 第三方登录接口
 */
class Third extends Api
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        // 增加事件 by Fire
        $auth = $this->auth;
        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = 0; // 修改登录时长 by Fire
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            $expire = 0; // 修改登录时长 by Fire
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
    }

    /**
     * 检测
     *
     * @param string $platform 平台名称
     * @param array $params 参数
     */
    public function check()
    {
        $platform   = $this->request->request("platform");
        $params     = json_decode(htmlspecialchars_decode($this->request->request('params')), true);

        if (!$platform || !$params) {
            $this->error(__('Invalid parameters'));
        } else {
            $time = time();
            $values = [
                'platform'      => $platform,
                'openid'        => $params['unionid'],
                'openname'      => isset($params['nickname']) ? $params['nickname'] : '',
                'access_token'  => $params['accessToken'],
                'refresh_token' => $params['refreshToken'],
                'expires_in'    => $params['expires'],
                'logintime'     => $time,
                'expiretime'    => $time + $params['expires'],
            ];
            $auth = \app\common\library\Auth::instance();

            if ($platform == 'qq' && $values['openid'] == '') {
                $response = Http::get('https://graph.qq.com/oauth2.0/me', ['access_token' => $params['accessToken'], 'unionid' => 1]);
                if (strpos($response, "callback") !== false) {
                    $lpos = strpos($response, "(");
                    $rpos = strrpos($response, ")");
                    $response = substr($response, $lpos + 1, $rpos - $lpos - 1);
                }
                $ret = json_decode($response, TRUE);
                $values['openid'] = $ret['unionid'];
            }

            // 判断openid是否存在
            $third = thirdModel::get(['platform' => $platform, 'openid' => $values['openid']]);
            if ($third) {
                $user = User::get($third['user_id']);
                if (!$user) {
                    $this->error('未绑定用户');
                }
                $third->save($values);
                $auth->direct($user->id);
                $data = ['userinfo' => $auth->getUserinfo()];
                $this->success('登录成功', $data);
            } else {
                $this->error('未绑定');
            }
        }
    }

    /**
     * 绑定
     *
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function bind()
    {
        $app = $this->request->request('app', '');
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        $platform = $this->request->request('platform');
        $params = json_decode(htmlspecialchars_decode($this->request->request('params')), true);
        $email = strtolower(Random::alnum(10)).'@0759home.com'; // 增加随机邮箱 by Fire

        if (!$mobile || !$captcha || !$platform || !$params) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('手机格式不正确');
        }
        if (!Sms::check($mobile, $captcha, 'userbind')) {
            $this->error('验证码不正确');
        }
        $time = time();
        $values = [
            'platform'      => $platform,
            'openid'        => $params['unionid'],
            'openname'      => isset($params['nickname']) ? $params['nickname'] : '',
            'access_token'  => $params['accessToken'],
            'refresh_token' => $params['refreshToken'],
            'expires_in'    => $params['expires'],
            'logintime'     => $time,
            'expiretime'    => $time + $params['expires'],
        ];
        $user = \app\common\model\User::getByMobile($mobile);
        $auth = \app\common\library\Auth::instance();
        if ($user) {
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $auth->register(Random::alnum(10), Random::alnum(10), $email, $mobile, [], $app); // 增加随机用户名和密码
            // 更新会员资料
            $fields = ['nickname' => $values['openname']];
            $user = User::get($auth->id);
            $user->save($fields);
        }
        if ($ret) {
            // 保存第三方信息
            if ($platform == 'qq' && $values['openid'] == '') {
                $response = Http::get('https://graph.qq.com/oauth2.0/me', ['access_token' => $params['accessToken'], 'unionid' => 1]);
                if (strpos($response, "callback") !== false) {
                    $lpos = strpos($response, "(");
                    $rpos = strrpos($response, ")");
                    $response = substr($response, $lpos + 1, $rpos - $lpos - 1);
                }
                $ret = json_decode($response, TRUE);
                $values['openid'] = $ret['unionid'];
            }
            $values['user_id'] = $auth->id;
            thirdModel::create($values);
            Sms::flush($mobile, 'userbind');
            $data = ['userinfo' => $auth->getUserinfo()];
            $this->success('登录成功', $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 下载第三方头像
     * by Fire
     */
    public function dl_third_avatar() {
        ini_set('default_socket_timeout', 1);
        $url = $this->request->request('url');
        $upload = Config::get('upload');
        $replaceArr = [
            '{module}'   => '/uploads',
            '{year}'     => date("Y"),
            '{mon}'      => date("m"),
            '{random32}' => Random::alnum(32),
            '{.suffix}'  => '.jpg'
        ];
        $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $upload['savekey']);

        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $fileName = substr($savekey, strripos($savekey, '/') + 1);
        $path = ROOT_PATH . 'public' . $uploadDir . $fileName;
        if (is_dir(ROOT_PATH . 'public' . $uploadDir) || mkdir(ROOT_PATH . 'public' . $uploadDir, 0755, true)) {
            $imgdata = @file_get_contents($url);
            @file_put_contents($path, $imgdata);
            if ($imgdata) {
                $img_data = getimagesize($path);
                $params = array(
                    'admin_id'    => 0,
                    'user_id'     => (int)$this->auth->id,
                    'filesize'    => filesize($path),
                    'imagewidth'  => $img_data[0],
                    'imageheight' => $img_data[1],
                    'imagetype'   => 'jpg',
                    'imageframes' => 0,
                    'mimetype'    => $img_data['mime'],
                    'url'         => $uploadDir . $fileName,
                    'uploadtime'  => time(),
                    'storage'     => 'local',
                    'sha1'        => hash_file('sha1', $url)
                );

                $attachment = model("attachment");
                $attachment->data(array_filter($params));
                $attachment->save();
                \think\Hook::listen("upload_after", $attachment);
                $user = $this->auth->getUser();
                $user->avatar = $uploadDir . $fileName;
                $user->save();
                $this->success(__('Upload successful'), [
                    'url' => $uploadDir . $fileName
                ]);
            }
        }
    }
}
